let id = location.search.substring(4)


initEditor()


$.ajax({
    url: '/my/category/list',
    success: function (res) {
        if (res.status === 0) {
            let str = ''
            res.data.forEach(function (item) {
                str += `<option value="${item.id}">${item.name}</option>`
            })
            $('#category').append(str)

            let form = layui.form
            form.render('select')
            $.ajax({
                url : '/my/article/' + id,
                success: function (res) {
                    console.log(res)
                    if (res.status === 0) {
                        let form = layui.form
                        form.val('article' , res.data)
                        $image.cropper('replace' , baseUrl + '/' + res.data.cover_img)
                    }
                }
            })
        }
    }
})


var $image = $('#image');
// - 设置配置项
var option = {
    autoCropArea : 1,
    // 纵横比(宽高比)
    aspectRatio: 40/28, // 正方形
    // 指定预览区域
    preview: '.img-preview' // 指定预览区的类名（选择器）
};
// - 调用cropper方法，创建剪裁区
$image.cropper(option);

$('button:contains("选择封面")').on('click', function () {
    $('#file').trigger('click');
})

$('#file').on('change', function () {
    if (this.files.length > 0) {
        let fileObj = this.files[0]
        let url = URL.createObjectURL(fileObj)
        // $image.cropper('destroy').attr('src', url).cropper(option);
        $image.cropper('replace' , url)  
    }
})

$.ajax({
    url: '/my/category/list',
    success: function (res) {
        let str = ''
        res.data.forEach(function (item) {
            str += `
            <option value="${item.id}">${item.name}</option>
            `              
        })
        $('#category').append(str)
        let form = layui.form
        form.render('select')
    }
})

$('form').on('submit', function (e) {
    e.preventDefault()
    let fd = new FormData(this)
    fd.set('content', tinyMCE.activeEditor.getContent())
    fd.append('id' , id)
    let canvas = $image.cropper('getCroppedCanvas' , {width : 400,height:280})
    canvas.toBlob(function (blob) {
        fd.append('cover_img' , blob)
        $.ajax({
            type: 'POST',
            url : '/my/article/update',
            data: fd,
            processData: false,
            contentType: false,
            success: function (res) {
                if (res.status === 0) {
                    layer.msg(res.message, { time: 1500 }, function () {
                        location.href = './list.html'
                    });
                    // 添加成功，跳转到 文章列表 页面                  
                  }
            }
        })
    })
})